﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using EventProcessorLoadTester.EventProcessorService;

namespace EventProcessorLoadTester
{
    class Program
    {
        private static int threadCount = 10;
        private static int sleepMin = 0;
        private static int sleepMax = 50;
        private static ManualResetEvent StopEvent = new ManualResetEvent(false);
        private static int eventCount = -1;
        private static int eventCounter = 0;

        private static IServiceFacade service;
        private static Random RND = new Random();

        private static List<Thread> Threads = new List<Thread>();
        
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new ConsoleTraceListener(false));

            for (var i = 0; i < threadCount; i++)
            {
                Threads.Add(new Thread(ThreadProc) { Name = "Worker." + i, });
            }

            service = new ServiceFacadeClient();

            Console.Write("Press ENTER to start");
            Console.ReadLine();
            Threads.ForEach(i => i.Start());

            Console.Write("Press ENTER to stop");
            Console.ReadLine();

            StopEvent.Set();
            Threads.ForEach(i => i.Join(1000));
        }
    
        static void ThreadProc()
        {
            while(eventCount < 0 || eventCount > eventCounter)
            {
                try
                {
                    Interlocked.Increment(ref eventCounter);
                    var e = new CreateCustomerEvent()
                                {
                                    EventId = Guid.NewGuid(),
                                    Id = Guid.NewGuid(),
                                    NewName = "Teszt ügyfél " + Guid.NewGuid().ToString(),
                                };

                    service.SubmitEvent(e);
                } catch(Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }
                if (StopEvent.WaitOne(RND.Next(sleepMin, sleepMax)))
                    break;
            }
            Trace.WriteLine("All events submitted");
        }
    }
}
